package user

import (
	"context"
	"fmt"

	"golang.org/x/crypto/bcrypt"
)

const (
	AppName = "user"
)

type Service interface {
	CreateUser(context.Context, *CreateUserRequest) (*User, error)
	DeleteUser(context.Context, *DeleteUserRequest) error
	QueryUser(context.Context, *QueryUserRequest) (*User, error)
}

type CreateUserRequest struct {
	Username string `json:"username" gorm:"column:username"`
	Password string `json:"password"`
	Role     Role   `json:"role"`
	isHashed bool
	// Id       int64  `json:"id" gorm:"primaryKey`
}

func (req *CreateUserRequest) SetIsHashed() {
	req.isHashed = true
}

func (req *CreateUserRequest) Validate() error {
	if req.Username == "" || req.Password == "" {
		return fmt.Errorf("用户名或者密码需要填写")
	}
	return nil
}

func NewCreateUserRequest() *CreateUserRequest {
	return &CreateUserRequest{
		Role: ROLE_AUTHOR,
	}
}

func (req *CreateUserRequest) PasswordHash() {
	if req.isHashed {
		return
	}
	b, _ := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
	req.Password = string(b)
	req.isHashed = true
}

type DeleteUserRequest struct {
	Id int64 `json:"id"`
}

type QueryUserRequest struct {
	QueryUserBy         QueryUserBy `json:"queryuser_id"`
	QueryUserByUsername string      `json:"queryuser_username"`
}

func NewQueryUserRequestID(id string) *QueryUserRequest {
	return &QueryUserRequest{
		QueryUserByUsername: id,
	}
}

func NewQueryUserRequestName(name string) *QueryUserRequest {
	return &QueryUserRequest{
		QueryUserBy:         Query_UserBy_Username,
		QueryUserByUsername: name,
	}
}
